<template>
  <div class="main">
    <!-- 环境数据监测 -->
    <div class="farm-main">
      <div class="tr-sid">
        <div class="sid-head">选择鱼塘</div>
        <div class="sid-tree">
          <treeSide @treeselectvalue="treeselectvalue" />
        </div>
      </div>
      <div class="tab-box">
        <div class="tab-box-one">
          <div class="homeBaseImg">
            <img v-if="homeBaseImg" :src="homeBaseImg" alt="">
          </div>
          <vue-drag-resize v-for="(item, index) in dataitemList" :key="index" :x="item.xaxis" :y="item.yaxis" :h="25"
            :w="250" :is-active="true" :is-draggable="false" :is-resizable="false" :parent-limitation="true"
            @dragstop="mczilongmet">
            <div @click.prevent="setbottommet(item, index)">
              <greencard :nowselectdataitemid="nowselectdataitemid" :nowcardmessage="item" />
            </div>
          </vue-drag-resize>
          <!-- <div class="card-reminder">
            <div class="card-reminder-item card-reminder-blue">选中数据项</div>
            <div class="card-reminder-item card-reminder-green">正常范围值</div>
            <div class="card-reminder-item card-reminder-red">超过报警值</div>
          </div> -->
        </div>
        <div class="tab-box-two">
          <div class="card-style" @click="clickbottom(nowItemClick)">
            <bluecard :nowcardmessage="nowItemClick" />
          </div>
        </div>
      </div>
    </div>
    <el-dialog :title="fishPondName" :visible.sync="dialogVisible" width="80%">
      <div class="mydialog">
        <div class="zh-search">
          <div class="search-item">
            选择数据项:
            <el-select filterable clearable v-model="searchList.dataItemId" @change="handleSearch">
              <el-option v-for="(item, index) in echartsidelist" :key="index" :value="item.dataItemId"
                :label="item.dataItemName" />
            </el-select>
          </div>
          <div class="search-item">
            选择时间颗粒：
            <el-select filterable clearable v-model="interval" placeholder="请选择">
              <el-option label="全部" :value="1" />
              <el-option label="30分钟" :value="30" />
              <el-option label="60分钟" :value="60" />
              <el-option label="90分钟" :value="90" />
              <el-option label="120分钟" :value="120" />
              <el-option label="180分钟" :value="180" />
            </el-select>
          </div>
          <div class="search-item">
            选择时间：
            <el-date-picker v-model="searchList.date" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
              start-placeholder="开始日期" format="yyyy-MM-dd HH:mm:ss" end-placeholder="结束日期" align="right" />
          </div>
          <div class="zh-search-but" @click="debouncedQuery">查 询</div>
          <div class="zh-search-but" @click="queryHistoryExport">导 出</div>
        </div>
        <div class="changeEcharts">
          <el-button v-for="item, index in buttonList" :key="index" :type="buttonIndex == index ? 'primary' : ''"
            @click="changeEcharts(index)" :icon="item.icon">{{ item.name }}</el-button>
          <!-- <el-button :type="buttonType?'':'primary'">查看表格</el-button> -->
        </div>
        <div class="zh-main">
          <div class="zh-side">
            <div v-for="(item, index) in echartsidelist" :key="index"
              :class="item.ischecked ? 'zh-side-item-select' : 'zh-side-item'" @click="setitemchecked(index)">{{
                item.dataItemName }}</div>
          </div>
          <div v-show="buttonIndex == 0" class="zh-echart">
            <zhechart :nowwidth="'100%'" :nowheight="'400px'" :cdata="zhexiantulistone" :y-axis="yaxiosdataList" />
          </div>
          <div class="border-card" v-show="buttonIndex == 1">
            <el-tabs type="border-card">
              <el-tab-pane v-for="item, index in formDataList" :key="index" :label="item.name">
                <el-table border :data="item.dataList" style="width: 100%" :row-class-name="tableRowClassName" :default-sort = "{prop: 'collectDatetime', order: 'descending'}">
                  <el-table-column sortable prop="collectDatetime" label="采集时间">
                  </el-table-column>
                  <el-table-column sortable prop="value" label="采集值">
                  </el-table-column>
                  <el-table-column prop="manualDataFlag" label="采集方式">
                    <template slot-scope="scope">
                      <span :style="{ color: scope.row.manualDataFlag ? 'blue' : 'green' }">{{ scope.row.manualDataFlag ? '手动采集'
                        : '自动采集' }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import treeSide from "@/components/selectbutton/trelist.vue";
import zhechart from "@/components/Echarts/components/linechart/chartYaxios.vue";
import greencard from "./component/greencard.vue";
import bluecard from "./component/bluecard.vue";
import EnvironmentalDataMonitoringApi from "@/api/iot-monitoring/environmental-data-monitoring";     // 折线图获取
import MeteorologicalMonitoringApi from "@/api/iot-monitoring/meteorological-monitoring";            // 折线图导出
import { mymixin } from "@/utils/mixin";
import VueDragResize from "vue-drag-resize";
import { getToken } from '@/utils/auth';
import { debounce } from 'lodash';
export default {
  name: "EnvironmentalDataMonitoring",
  components: { treeSide, greencard, zhechart, bluecard, VueDragResize },
  mixins: [mymixin],
  data() {
    return {
      buttonList: [{
        icon: 'el-icon-data-line',
        name: '查看图表'
      },
      {
        icon: 'el-icon-tickets',
        name: '查看表格'
      }],
      buttonIndex: 0,
      interval: 30,
      weatherDataItemId: '',
      // 当前选中的数据项
      nowselectdataitemid: 0,
      // 当前选中的鱼塘id
      fishPondId: 0,
      // 弹框相关
      dialogVisible: false,
      searchList: {
        dataItemId: "",
        date: []
      },
      // 当前地块或地块组下的dataitem,不带环境数据
      echartsidelist: [],
      yaxiosdataList: [
        {
          type: "value",
          axisLabel: {
            fontSize: 10
          },
          min: 0
        }
      ],
      // echarts数据
      zhexiantulistone: {},
      // ---环境数据相关
      dataitemList: [],
      nowItemClick: undefined,
      nowclickdataindex: "",
      // 当前选中鱼塘名
      fishPondName: "",
      homeBaseImg: '',
      formDataList: [],
    }
  },
  watch: {},
  mounted() {
    this.homeBaseImg = getToken('homeBaseImg');
    let date = this.dateToFormattwo(new Date());
    this.searchList.date = [`${date} 00:00:00`,`${date} 23:59:59`];
    // this.$set(this.searchList,'data')
    console.log(this.searchList.data)
  },
  computed: {
    debouncedQuery() {
      return debounce(this.getforechartdata, 1000);
    }
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    changeEcharts(index) {
      this.buttonIndex = index
    },
    // 折线图导出
    queryHistoryExport() {
      // console.log('111111111111111111111this.searchList', this.searchList);
      console.log('this.interval', this.interval, '******');
      if (this.searchList.date.length == 0 || !this.interval) {
        this.$message.error('时间颗粒与起止时间必须选择！！！')
        return
      }
      let params = {
        interval: this.interval,
        dataItemId: this.searchList.dataItemId,
        endTime: this.dateToFormat(this.searchList.date[1]),
        startTime: this.dateToFormat(this.searchList.date[0])
      };
      MeteorologicalMonitoringApi.queryHistoryExport(params).then(res => {
        this.getFileNameAndDownload(res)
      })
    },
    // 点击树状触发方法
    treeselectvalue(e) {
      this.nowItemClick = undefined;
      this.fishPondId = e;
      this.getTableDataList(e);
    },
    // 设置选中的值
    setitemchecked(i) {
      this.echartsidelist[i].ischecked = !this.echartsidelist[i].ischecked;
      this.getforechartdata();
    },
    handleSearch(e) {
      console.log(e)
      this.echartsidelist.forEach(item => {
        if (e == item.dataItemId) {
          item.ischecked = true
        } else {
          item.ischecked = false
        }
      })
      this.getforechartdata();
    },
    // 处理当前鱼塘数据项,数据结构
    getdataitemside() {
      let listone = this.dataitemList
      listone.forEach((selitem, selindex) => {
        if (selitem.dataItemId === this.searchList.dataItemId) {
          listone[selindex].ischecked = true;
        } else {
          listone[selindex].ischecked = false;
        }
      });
      this.echartsidelist = listone;
      this.getforechartdata();
    },
    // 从此开始循环获取折线图
    getforechartdata() {
      this.formDataList = []
      this.zhexiantulistone = {};
      this.yaxiosdataList = [
        {
          min: 0,
          type: "value",
          offset: 0,
          axisLabel: {
            fontSize: 10,
            color: "#000"
          }
        }
      ];
      this.echartsidelist.forEach(item => {
        if (item.ischecked === true) {
          console.log(item)
          this.getzhexiandataleft(item.dataItemId, item.dataItemName);
        }
      });
    },
    // 获取折线图
    getzhexiandataleft(id, dataItemName) {
      let date = this.dateToFormattwo(new Date());
      let params = {
        interval:this.interval,
        dataItemId: id,
        endTime: `${date} 23:59:59`,
        startTime: `${date} 00:00:00`
      };
      if (this.searchList.date[0]) {
        params.startTime = this.dateToFormat(this.searchList.date[0]);
        params.endTime = this.dateToFormat(this.searchList.date[1]);
      }
      EnvironmentalDataMonitoringApi.queryHistoryByList(params).then(res => {
        console.log(res.data)
        let obj = { name: '' }
        obj.name = dataItemName;
        obj.dataList = JSON.parse(JSON.stringify(res.data));
        this.formDataList.push(obj)
        // dataItemName
        if (res.data.length > 0) {
          this.handingzhexiangone(res.data.reverse());
        } else {
          this.$message.warning("暂无折线图数据");
        }
      });
    },
    // 折线图数据处理
    handingzhexiangone(list) {
      let xAxisdata = [];
      let xData = ["zh"];
      let nowindex = 0;
      if (this.zhexiantulistone.seriesData) {
        nowindex = this.zhexiantulistone.seriesData.length;
        console.log(nowindex);
      }
      let seriesData = [
        {
          name: this.getdataitemname(list[0].dataItemId),
          type: "line",
          data: [],
          yAxisIndex: nowindex,
          barWidth: 10
        }
      ];
      list.forEach(item => {
        seriesData[0]["data"].push(item.value);
        // seriesData[1]["data"].push(item.value + 50000)
        let ggdate = this.dateToFormat(item.collectDatetime);
        xAxisdata.push(ggdate);
      });
      let oldserData = [];
      if (this.zhexiantulistone.seriesData) {
        oldserData = JSON.parse(
          JSON.stringify(this.zhexiantulistone.seriesData)
        );
      }
      // 新增一条y轴
      let oldyaxioslist = JSON.parse(JSON.stringify(this.yaxiosdataList));
      let zhoffset = 0;
      // if(oldserData.length === )
      if (oldserData.length >= 2) {
        zhoffset = (oldserData.length - 1) * 26;
      }
      // let zhoffset = oldserData.length * 20
      if (oldserData.length > 0) {
        this.yaxiosdataList = [
          ...oldyaxioslist,
          {
            type: "value",
            offset: zhoffset,
            axisLabel: {
              fontSize: 10,
              color: "#000"
            },
            min: 0
          }
        ];
        // console.log(this.yaxiosdataList)
      }
      // 新增一条数据
      this.zhexiantulistone = {
        grid: {
          left: "70",
          right: "80",
          bottom: 0,
          top: "10",
        },
        xAxisdata: xAxisdata,
        xData: xData,
        seriesData: [...seriesData, ...oldserData]
      };
      // this.yaxiosdataList.push(yaxiosdata)
    },
    // -----------
    // 点击下面的数据类别，展示弹框
    clickbottom(list) {
      // console.log(list);
      this.searchList.dataItemId = list.dataItemId;
      this.dialogVisible = true;
      this.getdataitemside();
    },
    // 点击上面的数据
    setbottommet(greenCardItem, i) {
      this.nowItemClick = greenCardItem;
      this.nowclickdataindex = i;
      if (greenCardItem) {
        let nowid = greenCardItem.dataItemId;
        this.nowselectdataitemid = nowid;
      }
    },
    // 获取数据项名称
    getdataitemname(id) {
      let name = "数据项名称";
      this.echartsidelist.forEach(item => {
        if (id === item.dataItemId) {
          name = item.dataItemName;
        }
      });
      return name;
    },
    closevisab() { },
    // 获取数据类型
    getTableDataList(e) {
      EnvironmentalDataMonitoringApi.queryNewByFishPondId({ fishPondId: e }).then(res => {
        let data = res.data;
        this.handingdataitem(data);
      });
    },
    // 获取数据类型位置及其图片
    async handingdataitem(list) {
      let newlist = [];
      console.log(list)
      list && list.forEach((itemone, indexone) => {
        // 过滤掉未配置数据类型坐标和非采集类型的数据项
        if (itemone.dataType && itemone.dataType.configFlag && (itemone.dataType.mainingControlTypeStr === "采集" || itemone.dataType.mainingControlTypeStr === "采集控制")) {
          let temp = {};
          temp.dataItemName = itemone.dataItemName;
          temp.dataItemId = itemone.dataItemId;
          temp.collectDatetime = itemone.dataCollectNew?.collectDatetime || "0000-00-00 00:00:00";
          temp.lastValue1 = parseFloat(itemone.dataCollectNew?.firstValue) || 0;
          temp.change = itemone.dataCollectNew?.firstValue - itemone.dataCollectNew?.thirdValue || 0;
          if (temp.change > 0) temp.status = 1;
          if (temp.change == 0) temp.status = 2;
          if (temp.change < 0) temp.status = 3;
          temp.xaxis = parseInt(itemone.dataType.xaxis);
          temp.yaxis = parseInt(itemone.dataType.yaxis);
          temp.unit = itemone.dataType.unit;
          temp.logoFileId = itemone.dataType.logoFileId;
          console.log(temp)
          newlist.push(temp);
        }
      });
      setTimeout(() => {
        this.dataitemList = newlist
      }, 200);
    },
    mczilongmet(e) { }
  }
};
</script>
<style lang="scss" scoped>
.vdr.active:before {
  display: none;
}

.vdr.active:hover {
  z-index: 1 !important;
}

::v-deep .el-select .el-input__inner {
  color: #fff !important;
}

// .#005d7b
::v-deep .el-dialog {
  background-color: #f0f3f7;

  .el-dialog__header {
    background-color: #237FC3;
    height: 50px;

    .el-dialog__title {
      color: #fff;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }
  }
}

.mydialog {
  width: 100%;
  height: 500px;

  .zh-search {
    width: 100%;
    height: 50px;
    display: flex;

    .search-item {
      margin-right: 20px;
      color: #000;

      ::v-deep .el-input__inner {
        color: #000 !important;
      }
    }

    .zh-search-but {
      color: #000;
      width: 70px;
      text-align: center;
      height: 30px;
      line-height: 30px;
      margin-left: 10px;
      cursor: pointer;
      border: #000 1px solid;
      border-radius: 10px;
      font-weight: 700;
    }
  }

  .changeEcharts {
    width: 100%;
    padding: 5px 10px;
    background: #fdfdfd;
  }

  .zh-main {
    height: 400px;
    width: 100%;
    display: flex;
    justify-content: space-between;

    .zh-side {
      border: aliceblue 1px solid;
      width: 40px;
      max-height: 468px;
      overflow-y: auto;
      overflow-x: hidden;
      font-size: 20px;

      .zh-side-item {
        width: 40px;
        color: aliceblue;
        font-weight: 500;
        display: flex;
        flex-direction: column;
        background-color: #2A94FC;
        border: aliceblue 1px solid;
        padding-right: 5px;
        padding-left: 5px;
        padding-top: 10px;
        padding-bottom: 10px;
        text-align: center;
        cursor: pointer;
        writing-mode: vertical-lr;
      }

      .zh-side-item-select {
        width: 40px;
        // height: 100px;
        color: aliceblue;
        font-weight: 600;
        display: flex;
        flex-direction: column;
        background-image: linear-gradient(#0cbac7, #4ceffe, #0bb9c6);
        border: aliceblue 1px solid;
        padding-right: 5px;
        padding-left: 5px;
        padding-top: 10px;
        padding-bottom: 10px;
        text-align: center;
        cursor: pointer;
        writing-mode: vertical-lr;
      }
    }

    .zh-side::-webkit-scrollbar {
      display: none;
    }

    // background-color: steelblue;
    .zh-echart {
      width: calc(100% - 80px);
      height: 350px;
    }
  }
}

.card-style {
  width: 300px;
  height: 80px;
  margin-right: 10px;
}

.main {
  width: 100%;
  height: calc(100% - 20px);
  margin: 10px 0;
  border: 1px solid #B1D2FF;
  background: #F2F2F2;
  box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.16);
}

.farm-main {
  width: calc(100% - 50px);
  height: calc(100% - 50px);
  margin: 25px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  .tr-sid {
    width: 240px;
    height: 100%;
    background-color: #fff;
    margin-right: 20px;

    .sid-head {
      width: 100%;
      height: 60px;
      font-weight: 400;
      color: #1a3f58;
      line-height: 60px;
      padding-top: 10px;
      font-size: 18px;
      text-align: center;
      border-bottom: #fff dashed 1px;
    }

    .sid-tree {
      width: 100%;
      height: calc(100% - 40px);
    }
  }

  .tab-box {
    width: calc(85% - 10px);
    // margin-right: 10px;
    height: 100%;
    // border: aqua 1px solid;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;

    .tab-box-one {
      position: relative;
      width: 100%;
      height: 85%;
      max-height: 600px;
      background-image: url("~@/assets/oth-img/fish-pond-background.jpg");
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-position: top;

      .homeBaseImg {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .card-reminder {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
        position: absolute;
        width: 126px;
        height: 92px;
        bottom: 20px;
        right: 20px;
        padding: 5px 5px 5px 20px;
        border: 1px solid #4896fc;
        border-radius: 10px;

        .card-reminder-item {
          position: relative;

          &::before {
            content: "";
            position: absolute;
            left: -15px;
            top: 3px;
            width: 10px;
            height: 10px;
            border-radius: 5px;
          }
        }

        .card-reminder-blue {
          &::before {
            background-color: #4598fc;
          }
        }

        .card-reminder-green {
          &::before {
            background-color: #20cd4b;
          }
        }

        .card-reminder-red {
          &::before {
            background-color: #ff5f62;
          }
        }
      }
    }

    .tab-box-two {
      width: 100%;
      height: 15%;
      display: flex;
      align-items: flex-end;
      overflow-x: auto;
      // padding: 10px;
    }
  }
}

.mydialog {
  color: #000000;

  .el-input__inner {
    color: #000000;
  }
}

.border-card {
  width: 100%;
  padding: 10px;
}

::v-deep .el-tabs {
  height: 100%;
  .el-tabs__content{
    height: calc(100% - 50px);
    overflow-y: auto;
  }
}
</style>
